import React, { useEffect, useState } from "react";
import { Button, Form, Input } from "antd-mobile";
import { Notify } from 'react-vant'
import { getCodeApi, telLoginApi } from "../../api";
import { useDebounce } from "../../hooks";
import { useNavigate } from "react-router-dom";
const Login = () => {
  const [form] = Form.useForm()
  const [tel, setTel] = useState("");
  const max = 60;
  const [time, setTime] = useState(max);
  let timer
  const navigate = useNavigate()
  const getCode = async () => {
    timer = setInterval(() => {
      setTime(prev => {
        if(prev <= 1) {
          clearInterval(timer)
          return max
        }
        return prev - 1
      })
    }, 1000)


    const resp = await getCodeApi(tel);
    console.log(resp.data.data);
    form.setFieldValue("telCode", resp.data.data)

  };
  const onFinish = useDebounce(async (value) => {
    console.log(value)
    const resp = await telLoginApi(value) ;
    console.log(resp.data)
    const { code, message, data } = resp.data;
    if(code === 200) {
      navigate('/')
      // Notify.show({ type: "primary", message: message })
      // alert(message)
    } else {
      // Notify.show({ type: 'danger', message: message })
      alert(message)
    }
  });

  useEffect(() => {
    return () => {
      // 销毁执行 
      clearInterval(timer)
    }
  }, [])
  return (
    <div>
      <Form form={form} onFinish={onFinish} footer={<Button type="submit" block>登陆</Button>}>
        <Form.Item
          name="tel"
          rules={[
            {
              required: true,
              message: "请输入手机号",
            },
            {
              pattern: /^1[3-9]\d{9}$/,
              message: "请输入正确的手机号"
            }
          ]}
        >
          <Input
            placeholder="请输入手机号"
            onChange={(value) => setTel(value)}
            value={tel}
          ></Input>
        </Form.Item>
        <Form.Item
          rules={[
            {
              required: true,
              message: "请输入验证码",
            },
            {
              pattern: /^\S*(?=\S{6,})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*? ])\S*$/,
              message: ''
            }
          ]}
          name="telCode"
          extra={<Button disabled={max !== time} onClick={() => getCode()}>{ max === time ? "获取验证码": `还剩${time}秒` }</Button>}
        >
          <Input placeholder="请输入验证码"></Input>
        </Form.Item>
      </Form>
    </div>
  );
};

export default Login;
